package com.zhida.gooutcrawler.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zhida.gooutcrawler.MyApp;
import com.zhida.gooutcrawler.R;
import com.zhida.gooutcrawler.activity.CrawlerActivity;
import com.zhida.gooutcrawler.adapter.ColumnAdapter;
import com.zhida.gooutcrawler.adapter.helper.EndlessRecyclerOnScrollListener;
import com.zhida.gooutcrawler.entity.Article;
import com.zhida.gooutcrawler.entity.ArticleDao;
import com.zhida.gooutcrawler.entity.Column;
import com.zhida.gooutcrawler.entity.DaoSession;
import com.zhida.gooutcrawler.mvpview.IColumnView;
import com.zhida.gooutcrawler.presenter.ColumnPresenter;
import com.zhida.gooutcrawler.spider.Spider;
import com.zhida.gooutcrawler.util.DialogUtil;
import com.zhida.gooutcrawler.widget.recycler.CommonRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.rx.RxDao;
import org.greenrobot.greendao.rx.RxQuery;

import java.util.List;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.Unbinder;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 加载显示某一栏目的所有文章
 * Created by Administrator on 2017-04-05.
 */

public class ColumnFragment extends BaseMvpFragment<IColumnView, ColumnPresenter> {

    @BindView(R.id.loadingView)
    ProgressBar mLoadingView;

    @BindView(R.id.recyclerView)
    CommonRecyclerView mRecyclerView;

    @BindView(R.id.contentView)
    SwipeRefreshLayout mContentView;

    /*@BindView(R.id.total_text)
    TextView mTotalText;

    @BindView(R.id.log_text)
    TextView mLogText;

    @BindView(R.id.loading)
    LinearLayout mLoading;*/

    Unbinder unbinder;

    private View loadMoreView;
    private View headerView;

    private final static String TAG = "ColumnFragment";

    public static final String COLUMN_NAME_KEY = "column_name";
    public static final String COLUMN_URL_KEY = "column_url";


    DaoSession daoSession;
    private ArticleDao articleDao;

    private ColumnAdapter mAdapter;

    private String name;
    private String url;

    private int page = 1;
    private int pageSize = 10;

    public static ColumnFragment newInstance(@NonNull Column column) {
        Bundle arguments = new Bundle();
        arguments.putString(COLUMN_NAME_KEY, column.getText());
        arguments.putString(COLUMN_URL_KEY, column.getHref());
        ColumnFragment columnFragment = new ColumnFragment();
        columnFragment.setArguments(arguments);
        return columnFragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_column;
    }

    @Override
    protected void initAllMembersView(View view, @Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        name = arguments.getString(COLUMN_NAME_KEY);
        url = arguments.getString(COLUMN_URL_KEY);
        System.out.println("栏目fragment生成，名字:" + name + ",url:" + url);

        //下拉刷新
        mContentView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
                loadCount();
            }
        });
        initRecycleView();
        initDao();
    }

    private void initRecycleView() {

        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLinearLayoutManager);

        //adapter
        mAdapter = new ColumnAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);

        //加载更多
        mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLinearLayoutManager) {
            @Override
            public void onLoadMore(int i) {
                loadMoreData();
            }
        });

        createHeaderView();
        createLoadMoreView();
    }

    private void createHeaderView() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_header, mRecyclerView, false);
        mAdapter.enableHeaderView();
        mAdapter.addHeaderView(headerView);
        Button clear = (Button) headerView.findViewById(R.id.btn_clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Observable.fromCallable(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        articleDao.queryBuilder()
                                .where(ArticleDao.Properties.Column.eq(name))
                                .buildDelete().executeDeleteWithoutDetachingEntities();
                        return null;
                    }
                }).subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        loadData();
                        DialogUtil.confirm(getActivity(), "已经清除全部");
                    }
                });

            }
        });
    }

    private void createLoadMoreView() {
        loadMoreView = LayoutInflater.from(getActivity()).inflate(R.layout.item_footer, mRecyclerView, false);
        mAdapter.enableFooterView();
        mAdapter.addFooterView(loadMoreView);
        loadMoreView.setVisibility(View.GONE);
    }

    private void initDao() {
        daoSession = ((MyApp) getActivity().getApplication()).getDaoSession();
        articleDao = daoSession.getArticleDao();

    }

    @NonNull
    @Override
    public ColumnPresenter createPresenter() {
        return new ColumnPresenter();
    }

    /*@OnClick({R.id.start, R.id.pause})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:
//                spider.start();
                Intent startIntent = new Intent(getActivity(), SpiderService.class);
                getActivity().startService(startIntent);

                break;
            case R.id.pause:
//                spider.pause();
                Intent stopIntent = new Intent(getActivity(), SpiderService.class);
                getActivity().stopService(stopIntent);

                break;
        }
    }*/

    @Override
    protected void onFirstVisable() {
        loadData();
        loadCount();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getArticles(final boolean loadmore) {

        if (loadmore) {
            page++;
        } else {
            page = 1;
        }

        RxQuery<Article> rxQuery = articleDao.queryBuilder()
                .where(ArticleDao.Properties.Column.eq(name))
                .orderDesc(ArticleDao.Properties.Time)
                .offset((page - 1) * pageSize)
                .limit(pageSize)
                .rx();

        rxQuery.list()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<Article>>() {
                    @Override
                    public void call(List<Article> notes) {
                        if (loadmore) {
                            onLoadMore(notes);
                        } else {
                            onLoad(notes);
                        }
                    }
                });

    }

    /**
     * 加载第一页数据，用于初始化的时候和刷新的时候
     */
    private void loadData() {
        getArticles(false);
        loadMoreView.setVisibility(View.VISIBLE);
    }

    /**
     * 加载更多数据
     */
    private void loadMoreData() {
        getArticles(true);
        loadMoreView.setVisibility(View.VISIBLE);
    }

    private void loadCount() {
        //获取总数
        Observable.fromCallable(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return articleDao.queryBuilder()
                        .where(ArticleDao.Properties.Column.eq(name))
                        .buildCount().count();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long l) {
                        EventBus.getDefault().post(new OnColumnRefreshEvent(name, l));
                    }
                });
    }

    /* 加载完成 */
    public void finishLoad(Integer size) {
        if (size < pageSize) {
            //没有更多了
            TextView textView = (TextView) loadMoreView.findViewById(R.id.footer_text);
            textView.setText("没有更多了");
            loadMoreView.findViewById(R.id.progressBar).setVisibility(View.GONE);
            loadMoreView.setVisibility(View.VISIBLE);
        } else {
            loadMoreView.setVisibility(View.GONE);
        }
        mContentView.setRefreshing(false);
        mLoadingView.setVisibility(View.GONE);
    }

    public void onLoad(List<Article> articles) {
        mAdapter.reset(articles);
        finishLoad(articles.size());
    }

    public void onLoadMore(List<Article> articles) {
        mAdapter.addAll(articles);
        finishLoad(articles.size());
    }

    //eventbus

    public static class OnColumnRefreshEvent {
        private long total;
        private String columnName;

        public OnColumnRefreshEvent(String columnName, long total) {
            this.columnName = columnName;
            this.total = total;
        }

        public long getTotal() {
            return total;
        }

        public String getColumnName() {
            return columnName;
        }
    }

}
